const app = getApp()

Page({
  data: {
    categories: [
      { id: 1, name: '金属', icon: '/assets/images/metal.png' },
      { id: 2, name: '塑料', icon: '/assets/images/plastic.png' },
      { id: 3, name: '纸类', icon: '/assets/images/paper.png' },
      { id: 4, name: '电器', icon: '/assets/images/electronics.png' },
      { id: 5, name: '玻璃', icon: '/assets/images/glass.png' },
      { id: 6, name: '织物', icon: '/assets/images/textile.png' },
      { id: 7, name: '其他', icon: '/assets/images/other.png' }
    ],
    selectedCategory: null,
    wasteTypes: [],
    searchQuery: '',
    selectedCount: 0
  },

  onLoad() {
    this.loadWasteTypes()
  },

  loadWasteTypes() {
    const { selectedCategory, searchQuery } = this.data
    let url = `${app.globalData.baseUrl}/pricing/waste-types/`
    
    // 添加查询参数
    const params = []
    if (selectedCategory) {
      params.push(`category=${selectedCategory}`)
    }
    if (searchQuery) {
      params.push(`search=${searchQuery}`)
    }
    if (params.length > 0) {
      url += '?' + params.join('&')
    }

    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          const wasteTypes = (res.data.results || res.data).map(waste => ({
            ...waste,
            selected: false
          }))
          this.setData({ wasteTypes })
        }
      }
    })
  },

  selectCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    this.setData({
      selectedCategory: this.data.selectedCategory === categoryId ? null : categoryId
    }, () => {
      this.loadWasteTypes()
    })
  },

  onSearch(e) {
    const searchQuery = e.detail.value
    this.setData({ searchQuery }, () => {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      this.searchTimeout = setTimeout(() => {
        this.loadWasteTypes()
      }, 500)
    })
  },

  toggleSelect(e) {
    const id = e.currentTarget.dataset.id
    const wasteTypes = this.data.wasteTypes.map(waste => {
      if (waste.id === id) {
        return { ...waste, selected: !waste.selected }
      }
      return waste
    })
    
    const selectedCount = wasteTypes.filter(waste => waste.selected).length
    
    this.setData({
      wasteTypes,
      selectedCount
    })
  },

  confirmSelection() {
    const selectedWastes = this.data.wasteTypes.filter(waste => waste.selected)
    
    if (selectedWastes.length === 0) {
      wx.showToast({
        title: '请至少选择一种废品',
        icon: 'none'
      })
      return
    }

    // 获取上一页实例
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    // 调用上一页的方法，传递选中的废品数据
    prevPage.onWasteSelected(selectedWastes)
    
    wx.navigateBack()
  }
}) 